package com.sch.www.oauth;

import com.sch.www.common.base.ResultBean;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;


@ControllerAdvice()
public class GlobalExceptionHandler {

    @ExceptionHandler(OAuth2Exception.class)
    @ResponseBody
    public ResultBean exceptionHandler(OAuth2Exception e, HttpServletResponse response) {

        String errorCode = e.getOAuth2ErrorCode();
        String msg;
        if (OAuth2Exception.INVALID_CLIENT.equals(errorCode)) {
            msg = "client验证失败";
        } else if (OAuth2Exception.UNAUTHORIZED_CLIENT.equals(errorCode)) {
            msg = "client未受权";
        } else if (OAuth2Exception.INVALID_GRANT.equals(errorCode)) {
            msg = "用户名或密码验证失败";
        } else if (OAuth2Exception.INVALID_SCOPE.equals(errorCode)) {
            msg = "scope验证失败";
        } else if (OAuth2Exception.INVALID_TOKEN.equals(errorCode)) {
            msg = "token验证失败";
        } else if (OAuth2Exception.INVALID_REQUEST.equals(errorCode)) {
            msg = "请求验证失败";
        } else if (OAuth2Exception.REDIRECT_URI_MISMATCH.equals(errorCode)) {
            msg = "重定向的链接不匹配";
        } else if (OAuth2Exception.UNSUPPORTED_GRANT_TYPE.equals(errorCode)) {
            msg = "不支持该受权类型";
        } else if (OAuth2Exception.UNSUPPORTED_RESPONSE_TYPE.equals(errorCode)) {
            msg = "不支持该返回类型";
        } else if (OAuth2Exception.ACCESS_DENIED.equals(errorCode)) {
            msg = "访问被拒绝";
        } else {
            msg = "异常";
        }
        ResultBean<OAuth2Exception> resultBean = ResultBean.newInstance();
        resultBean.setHttpStatus(HttpStatus.BAD_REQUEST).setError().setMsg(msg).setData(e);

        return resultBean;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultBean exceptionHandler(Exception e, HttpServletResponse response) {
        ResultBean<Exception> resultBean = ResultBean.newInstance();
        resultBean.setHttpStatus(HttpStatus.BAD_REQUEST).setError().setMsg(e.getMessage()).setData(e);
        return resultBean;
    }


}